package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CoreFetcherUtils;
import com.lehecai.core.util.CoreStringUtils;

/**
 * @author Sunshow
 *
 */
public abstract class AbstractLotteryDrawFetchWorker {
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    protected final static String PROXY_URL = "http://internal.data.lecai.com/api/proxy/fetch.do";

    protected static enum METHOD {
        GET,
        POST,
    }

	private LotteryType lotteryType;
	
	abstract public LotteryDraw fetchResult(String phase);
	abstract public LotteryDraw fetchResultDetail(String phase);
	
	abstract protected String getResultDetailUrl(String phase);
	abstract protected String getResultUrl(String phase);
	
	protected AbstractLotteryDrawFetchWorker() {
		
	}
	
	protected AbstractLotteryDrawFetchWorker(LotteryType lotteryType) {
		this.lotteryType = lotteryType;
	}
	
	public LotteryType getLotteryType() {
		return lotteryType;
	}

    protected boolean usingProxy() {
        return false;
    }

    protected String fetch(String url, METHOD method, Map<String, String> headerParams, Map<String, String> requestParams, String encoding) {
        String fetchUrl = url;

        if (this.usingProxy()) {
            if (headerParams == null) {
                headerParams = new HashMap<String, String>();
            }

            fetchUrl = PROXY_URL + "?enc=" + encoding + "&" + CoreStringUtils.md5(url, encoding);

            headerParams.put("X-REAL-REQUEST", url);
        }
        
        String content;
        switch (method) {
            case GET:
                content = CoreFetcherUtils.URLGetWithHeaderParams(fetchUrl, headerParams, requestParams, encoding);
                if (content == null || content.isEmpty()) {
                    return null;
                }
                return content;
            case POST:
                content = CoreFetcherUtils.URLPostWithHeaderParams(fetchUrl, headerParams, requestParams, encoding);
                if (content == null || content.isEmpty()) {
                    return null;
                }
                return content;
            default:
                return null;
        }
    }
}
